package org.grow.leavejpa.service;

import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.grow.leavejpa.entity.QPermission;
import org.grow.leavejpa.entity.QPermissionRole;
import org.grow.leavejpa.entity.QRoleInfo;
import org.grow.leavejpa.entity.RoleInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;

import javax.servlet.Filter;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.stream.Collectors;

/**
 * @Author: xwg
 * @CreateDate: 21-6-16
 */
@Service
public class PermissionDataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private JPAQueryFactory jpaQueryFactory;
//    Filter
    QRoleInfo r = QRoleInfo.roleInfo;
    QPermission p = QPermission.permission;
    QPermissionRole pr = QPermissionRole.permissionRole;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        FilterInvocation  filterInvocation = (FilterInvocation) o;
//        HttpServletRequest httpRequest = filterInvocation.getHttpRequest();
        String uri = filterInvocation.getRequestUrl();
        HttpServletRequest httpRequest = filterInvocation.getHttpRequest();
        String method = httpRequest.getMethod().toUpperCase();
        System.out.println("datasource: 用户想要访问： "+uri);

//
//        String uri = "/leaveAbout/leave/submit/13";
        List<RoleInfo> fetch = jpaQueryFactory.select(r).from(p)
                .leftJoin(pr).on(p.permissionId.eq(pr.permissionFk))
                .leftJoin(r).on(pr.roleFk.eq(r.roleId))
                .where(Expressions.booleanTemplate("{0} like {1}", uri, p.pathPattern))
                .where(p.httpMethod.eq(HttpMethod.valueOf(method)))
                .fetch();
        System.out.println("datasource: 根据uri查询出的角色信息: "+fetch);
        List k = fetch;
        return k;

//        Collection<Object> objects = new ArrayList<>();

//        System.out.println("datasource: 当前用户根据url查询到的角色 "+fetch);

//        return fetch.stream()
//                .map(x -> {
//                    return new SecurityConfig(x.getRoleName());
//                }).collect(Collectors.toList());

    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
